package com.gxy.learn.design.model.create.singleton;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Constructor;

/**
 * @description: 用来测试实现序列化接口后进行反射调用时会不会破坏单例
 * @author: gaoxueyong
 * @Date: 2022/11/6 16:57
 */
@Slf4j
public class ClientInvokeTest {
    public static void main(String[] args) throws Exception {
//        test2();
//        test();
//        breakTest();

    }

    public static void test() throws Exception {
        Class classzz = SingletonSluggardStatic.class;
//        获取无参构造对象
        Constructor declaredConstructors = classzz.getDeclaredConstructor();
//        取消访问检查
        declaredConstructors.setAccessible(true);
        SingletonSluggardStatic single1 = (SingletonSluggardStatic) declaredConstructors.newInstance();
        SingletonSluggardStatic single2 = (SingletonSluggardStatic) declaredConstructors.newInstance();
        log.info("SingletonSluggardStatic - 反射是否破坏单例完整性 true 代表未破坏 false 代表已破坏 -最终结果：{}", single1 == single2);

    }
    public static void test2() throws Exception {
        Class classzz = SingletonHungryStaticCode.class;
//        获取无参构造对象
        Constructor declaredConstructors = classzz.getDeclaredConstructor();
//        取消访问检查
        declaredConstructors.setAccessible(true);
        SingletonHungryStaticCode single1 = (SingletonHungryStaticCode) declaredConstructors.newInstance();
        SingletonHungryStaticCode single2 = (SingletonHungryStaticCode) declaredConstructors.newInstance();
        log.info("SingletonHungryStaticCode - 反射是否破坏单例完整性 true 代表未破坏 false 代表已破坏 -最终结果：{}", single1 == single2);

    }

    public static void breakTest() throws Exception {
        Class classzz = SingletonSluggardStaticInvokeSerializable.class;
//        获取无参构造对象
        Constructor declaredConstructors = classzz.getDeclaredConstructor();
//        取消访问检查
        declaredConstructors.setAccessible(true);
        SingletonSluggardStaticInvokeSerializable single1 = (SingletonSluggardStaticInvokeSerializable) declaredConstructors.newInstance();
        SingletonSluggardStaticInvokeSerializable single2 = (SingletonSluggardStaticInvokeSerializable) declaredConstructors.newInstance();
        log.info("反射是否破坏单例完整性 true 代表未破坏 false 代表已破坏 -最终结果：{}", single1 == single2);
    }
}
